package com.jtech.together.mvp.presenter;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.jtech.together.manager.UserManager;
import com.jtech.together.mvp.contract.MainContract;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.core.ConnectionStatus;
import cn.bmob.newim.listener.ConnectListener;
import cn.bmob.newim.listener.ConnectStatusChangeListener;
import cn.bmob.v3.exception.BmobException;

/**
 * 主页
 * Created by wuxubaiyang on 2017/5/10.
 */
public class MainPresenter implements MainContract.Presenter {
    private Context context;
    private MainContract.View view;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://尝试重连
                    connectIM();
                    break;
            }
        }
    };

    public MainPresenter(Context context, MainContract.View view, Bundle bundle) {
        this.context = context;
        this.view = view;
        //监听即时通讯连接状态
        BmobIM.getInstance()
                .setOnConnectStatusChangeListener(new OnIMConnectionStatusChange());
    }

    @Override
    public void connectIM() {
        if (!UserManager.isLogin()) {
            return;
        }
        BmobIM.connect(UserManager.getCurrentUser().getObjectId(), new ConnectListener() {
            @Override
            public void done(String s, BmobException e) {
                //连接失败则尝试定时重连
                if (null != e) {
                    if (!handler.hasMessages(0)) {
                        handler.sendEmptyMessageDelayed(0, 1000);
                    }
                }
            }
        });
    }


    /**
     * 即时通讯连接状态
     */
    private class OnIMConnectionStatusChange extends ConnectStatusChangeListener {
        @Override
        public void onChange(ConnectionStatus connectionStatus) {
            Log.i("IMConnectionStatus", "onChange: " + connectionStatus.getMsg());
            //如果连接失败则重试
            if (ConnectionStatus.DISCONNECT.getCode() == connectionStatus.getCode()) {
                //尝试重连
                handler.sendEmptyMessage(0);
            }
            if (ConnectionStatus.NETWORK_UNAVAILABLE.getCode() == connectionStatus.getCode()) {
                //当失去连接的时候则尝试定时重连
                if (!handler.hasMessages(0)) {
                    handler.sendEmptyMessageDelayed(0, 1000);
                }
            }
        }
    }
}